package com.reny.ll.git.base_logic.api

import com.reny.ll.git.base_logic.api.request.RequestObj
import com.reny.ll.git.base_logic.model.BeanWrap
import retrofit2.Response
import java.io.IOException

val OK: Int = 0//约定的正确返回码
val JUMP_LOGIN = 401 //可能在其它地方登录
val PAST_DUE: Int = 107 //身份过期状态码

fun <T> Response<BeanWrap<T>>.process(): T?{
    try {
        val responseCode = this.code()
        val responseMessage = this.message()
        if (this.isSuccessful) {
            this.body()?.let {
                when (it.code) {
                    OK -> {
                        return it.data
                    }
                    else -> {
                        //loge("error: code = ${it.code}")
                        if (it.code == JUMP_LOGIN) {//需要登录
                            /*if (!isFastReq()) {
                                clearUser()
                                checkLogin()
                            }*/
                        }

                        throw HttpException(it.code, it.msg)
                        //return Results.failure(HttpException(it.code, it.msg))
                    }
                }
            }
            return this.body()?.data
        } else {
            this.errorBody()?.let {
                try {
                    val data: BeanWrap<*> = RequestObj.gson.fromJson(it.string(), BeanWrap::class.java)
                    throw HttpException(data.code, data.msg)
                }catch (e : Exception){e.printStackTrace()}
            }
            throw HttpException(responseCode, responseMessage)
            //Results.failure(HttpException(responseCode, responseMessage))
        }
    } catch (e: IOException) {
        throw HttpException(message = e.message)
        //Results.failure(HttpException(message = e.message))
    }
}